package com.xinbochuang.machine.admin.service.impl.system;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinbochuang.machine.admin.domain.system.SysDictData;
import com.xinbochuang.machine.admin.domain.system.SysDictType;
import com.xinbochuang.machine.admin.mapper.system.SysDictTypeMapper;
import com.xinbochuang.machine.admin.service.system.ISysDictDataService;
import com.xinbochuang.machine.admin.service.system.ISysDictTypeService;
import com.xinbochuang.machine.common.constant.UserConstants;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.exception.CustomException;
import com.xinbochuang.machine.common.utils.DictUtils;
import com.xinbochuang.machine.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author 黄晓鹏
 * @date 2020-09-18
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private SysDictTypeMapper dictTypeMapper;

    @Resource
    private ISysDictDataService dictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        List<SysDictType> dictTypeList = list(null);
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDataList = dictDataService.selectDictDataByType(dictType.getDictType());
            DictUtils.setDictCache(dictType.getDictType(), dictDataList);
        }
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public TableDataInfo selectDictTypeList(SysDictType dictType) {
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(SysDictType::getDictId);
        if (dictType != null) {
            if (StrUtil.isNotBlank(dictType.getDictName())) {
                queryWrapper.lambda().like(SysDictType::getDictName, dictType.getDictName());
            }
            if (StrUtil.isNotBlank(dictType.getStatus())) {
                queryWrapper.lambda().eq(SysDictType::getStatus, dictType.getStatus());
            }
            if (StrUtil.isNotBlank(dictType.getDictType())) {
                queryWrapper.lambda().like(SysDictType::getDictType, dictType.getDictType());
            }
            if (StrUtil.isNotBlank(dictType.getBeginTime()) && StrUtil.isNotBlank(dictType.getEndTime())) {
                queryWrapper.lambda().between(SysDictType::getCreateTime, dictType.getBeginTime(), dictType.getEndTime());
            }
        }
        List<SysDictType> dictTypeList;
        IPage<SysDictType> list = new Page<>();
        if (dictType.getPageNum() == null) {
            dictTypeList = list(queryWrapper);
            list.setRecords(dictTypeList);
            list.setTotal(dictTypeList.size());
        } else {
            list = page(new Page<>(dictType.getPageNum(), dictType.getPageSize()), queryWrapper);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.HTTP_OK);
        rspData.setMsg("查询成功");
        rspData.setRows(list.getRecords());
        rspData.setTotal(list.getTotal());
        return rspData;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Integer dictId) {
        return getById(dictId);
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dictType 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dictType) {
        int dictId = dictType.getDictId() != null ? dictType.getDictId() : -1;
        SysDictType info = getOne(Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictType, dictType.getDictType()).last("and rownum = 1"));
        if (info != null && dictId != info.getDictId()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    public boolean insertDictType(SysDictType dictType) {
        boolean result = save(dictType);
        if (result) {
            DictUtils.clearDictCache();
        }
        return result;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dictType 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDictType(SysDictType dictType) {
        SysDictType oldDict = getById(dictType.getDictId());
        SysDictData dictData = new SysDictData();
        dictData.setDictType(dictType.getDictType());
        dictDataService.update(dictData, Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictType, oldDict.getDictType()));
        boolean result = update(dictType, Wrappers.<SysDictType>lambdaQuery().eq(SysDictType::getDictType, oldDict.getDictType()));
        if (result) {
            DictUtils.clearDictCache();
        }
        return result;
    }

    /**
     * 批量删除字典信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public boolean deleteDictTypeByIds(Integer[] dictIds) {
        for (Integer dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataService.count(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictType, dictType.getDictType())) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
        }
        boolean result = removeByIds(Arrays.asList(dictIds));
        if (result) {
            DictUtils.clearDictCache();
        }
        return result;
    }

    /**
     * 清空缓存数据
     */
    @Override
    public void clearCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 查询所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return list(null);
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = dictDataService.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }
}
